package com.lyn.qrcode;

import android.graphics.Rect;

import com.yanzhenjie.zbar.Image;
import com.yanzhenjie.zbar.ImageScanner;
import com.yanzhenjie.zbar.Symbol;
import com.yanzhenjie.zbar.SymbolSet;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Zbar 二维码管理器
 *
 * @author Lyn 2022/12/25
 * @version 1.0.0
 */
 class ZbarManager {

    private final ImageScanner imageScanner;
    private final Image image;


    public ZbarManager() {
        imageScanner = new ImageScanner();
        image = new Image();
    }


    private final List<QrCodeInfo> qrCodeInfoList = new CopyOnWriteArrayList<>();


    public List<QrCodeInfo> decode(byte[] nv21Data, int nv21Width, int nv21Height) {
        image.setSize(nv21Width, nv21Height);
        image.setData(nv21Data);
        qrCodeInfoList.clear();
        int result = imageScanner.scanImage(image);
        if (result == 0) {
            qrCodeInfoList.clear();
            return qrCodeInfoList;
        }
        SymbolSet symSet = imageScanner.getResults();
        for (Symbol sym : symSet) {
            if (sym == null) {
                continue;
            }
            int[] coordinate = sym.getBounds();
            Rect rect = new Rect();
            rect.left = coordinate[0];
            rect.top = coordinate[1];
            rect.right = (coordinate[0] + coordinate[2]);
            rect.bottom = (coordinate[1] + coordinate[3]);
            QrCodeInfo qrCodeQrCodeInfo = new QrCodeInfo(sym.getData(), rect, System.currentTimeMillis());
            qrCodeInfoList.add(qrCodeQrCodeInfo);
        }
        return qrCodeInfoList;
    }

    public void destroy() {
        imageScanner.destroy();
        image.destroy();
    }
}
